package bio.socket;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Instruction：
 * Author：@author MaLi
 */
public class FileTransferServer {
    public void startServer() {
        try {
            ServerSocket socketServer = new ServerSocket(8888);
            while (!Thread.interrupted()) {
                Socket socket = socketServer.accept();
                //创建一个线程, 处理任务
                new Thread(()->{
                    try {
                        String resquestFileName = getFileName(socket);
                        sendFile(socket, resquestFileName);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private String getFileName(Socket socket) throws IOException {
        //输出一条消息: 询问获取哪个文件
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //获取文件名
        String resquestFileName = reader.readLine().trim();
        return resquestFileName;
    }

    private void sendFile(Socket socket, String resquestFileName) throws IOException {
        //传输文件
        try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(resquestFileName));
             BufferedOutputStream outputStream = new BufferedOutputStream(socket.getOutputStream())) {
            int length;
            byte[] buffer = new byte[8192];
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.flush();
        }
    }

    public static void main(String[] args) {
        new FileTransferServer().startServer();
    }
}
